/**
******************************************************************************
* @File:
* @Author:	Ares
* @Revision:
* @Date:
* @Brief:
******************************************************************************
* @attention
*
******************************************************************************
*/
#include "fx.h"
#include "string.h"
#include "util.h"
#include "sys.h"
#include "cJSON.h"
#include "dev.h"

Fx_Obj fx;

void fx_proc_get(char *cmd, int len)
{
}

void fx_proc_control(char *cmd, int len)
{
}

void fx_proc_set(char *cmd, int len)
{
	cJSON *reply=cJSON_CreateObject();
	cJSON *root=cJSON_Parse(cmd);
	cJSON *key=NULL;
	Aliyun_Obj *ali=&gSys.ali;
	char reply_topic[128]={0};
	char reply_reason[64]={0};
	char *reply_msg;
	int ret;
	
	//ʶ����������
	key=cJSON_GetObjectItem(root,"cmd");
	if(!strcmp(key->valuestring,"infor"))
	{
		ret=fx_basic_param_set(cmd,reply_reason);
	}
	if(!strcmp(key->valuestring,"timing"))
	{
		ret=fx_fix_time(cmd,reply_reason);
	}
	
	//构造应答对象
	key=cJSON_GetObjectItem(root,"id");
	cJSON_AddItemToObject(reply,"id",cJSON_CreateString(key->valuestring));
	key=cJSON_GetObjectItem(root,"cmd");
	cJSON_AddItemToObject(reply,"cmd",cJSON_CreateString(key->valuestring));
	cJSON_AddItemToObject(reply,"result",cJSON_CreateNumber(ret));
	cJSON_AddItemToObject(reply,"message",cJSON_CreateString(reply_reason));
	//构造应答topic
	sprintf(reply_topic,"/%s/%s/set/response",ali->ProductKey,ali->DeviceName);
	//构造应答消息
	reply_msg=cJSON_Print(reply);
	cJSON_Minify(reply_msg);
	//发送应答消息
	mqtt_pub((u8*)reply_topic,reply_msg);

	//释放命令对象
	cJSON_Delete(root);
	//释放应答对象
	cJSON_Delete(reply);
	//释放应答消息
	cJSON_free(reply_msg);
}

static void fake_set(void)
{
	RealTime_Obj *rt=&fx.realtime_param;
	rt->energy=(double)1/3;
	rt->power=10;
	rt->runTime=123456;
	rt->standy=(double)1/3;
	rt->accStatus=1;
	rt->relayStatus=2;
	rt->stragyStatus=4;
	rt->temp=(double)23.7;
}

void fx_load2sys(void)
{
	gSys.timer.report_timer	=	fx.basic_param.reportElapse*60;
}

void ExternalProtocolInit(void)
{
	//初始化协议
	memset(&fx,0,sizeof(Fx_Obj));
	//配置协议
	fake_set();
	//检查基础数据
	fx_basic_param_chk();
	//加载数据
	fx_load2sys();
}